package com.example.monthmoni.config;

import com.example.monthmoni.filter.LoginProcessFilter;
import com.example.monthmoni.security.AuthFaileHandler;
import com.example.monthmoni.security.AuthenricationEnriy;
import com.example.monthmoni.security.MyDeniedHandler;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author 宋伟宁
 * @Date 2023/11/28
 * @Version 1.0
 **/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    private static final String[] AUTH_WHITELIST = {
           "/login",
            "/logout",
            "/webjars/**"
    };
    @Resource
    private LoginProcessFilter loginProcessFilter;
    @Resource
    private AuthenricationEnriy authenricationEnriy;
    @Resource
    private MyDeniedHandler myDeniedHandler;
    @Resource
    private AuthFaileHandler authFaileHandler;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
             http.authorizeHttpRequests(auths->
                      auths.requestMatchers(AUTH_WHITELIST).permitAll()
                              .anyRequest().authenticated()

                     );

             http.formLogin(form->
                        form.loginPage("/login").permitAll()
                                .defaultSuccessUrl("/index")
                                .failureHandler(this.authFaileHandler)

                     );

             http.csrf(csrf->csrf.disable());
             //记着：前后端分离时要禁用session
             //http.sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
             http.exceptionHandling( e->e.authenticationEntryPoint(this.authenricationEnriy));
             http.exceptionHandling( e->e.accessDeniedHandler(this.myDeniedHandler));
             http.addFilterBefore(this.loginProcessFilter, UsernamePasswordAuthenticationFilter.class);

             return http.build();
    }


    @Bean
    PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }
}
